package com.luhuiguo.contacts.server.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.luhuiguo.contacts.server.service.ContactService;
import com.luhuiguo.contacts.shared.entity.Contact;
import com.luhuiguo.contacts.shared.rpc.CreateContact;
import com.luhuiguo.contacts.shared.rpc.CreateContactResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;
import com.luhuiguo.gwt.validation.server.ServerValidation;

@Component
public class CreateContactHandler implements ActionHandler<CreateContact, CreateContactResult> {

    @Autowired
    private ContactService contactService;

    @Override
    public CreateContactResult execute(CreateContact action, ExecutionContext context) throws ActionException {

        Contact contact = action.getContact();

        new ServerValidation(false).length(contact.getName(), 1, 50, "name").length(contact.getPhone(), 1, 50, "phone")
                .length(contact.getCompany(), 1, 100, "company").length(contact.getNote(),0, 250, "note").validate();

        try {

            contactService.createContact(contact);
            CreateContactResult result = new CreateContactResult(contact);
            return result;
        } catch (Exception e) {
            throw new ActionException("Error while creating contact " + action.getContact(), e);
        }
    }

    @Override
    public Class<CreateContact> getActionType() {
        return CreateContact.class;
    }

    @Override
    public void rollback(CreateContact action, CreateContactResult result, ExecutionContext context)
            throws ActionException {

    }

}
